package impl

import (
	"context"
	"fmt"
	"strings"
	"vblog/apps/user"
	"vblog/common"
	"vblog/exception"

	"gorm.io/gorm"
)

// 创建用户
func (c *UserServiceImpl) CreateUser(ctx context.Context, in *user.CreateUserRequest) (ins *user.User, err error) {

	in.Username = strings.TrimSpace(in.Username)
	if len(in.Username) == 0 {
		return nil, user.ErrorNotSpaces
	}

	in.Password = strings.TrimSpace(in.Password)
	if len(in.Password) == 0 {
		return nil, user.ErrorNotSpaces
	}
	// 校验
	if err := common.Validate(in); err != nil {
		return nil, err
	}
	//
	// ins = user.NewUser(in)

	//查询用户 DescribeUser
	// err = c.UserModel().WithContext(ctx).Where("username = ?", in.Username).First(&ins).Error
	_, err = c.DescribeUser(ctx, &user.DescribeUserRequest{Username: in.Username})

	if err != nil && err.Error() != gorm.ErrRecordNotFound.Error() {
		// fmt.Println(err.Error(), gorm.ErrRecordNotFound.Error())
		return nil, err
	}

	// if ins.Id > 0 {
	// 	return nil, user.ErrorUserExists
	// }

	// User
	ins = user.NewUser(in)

	// 密码加密
	hashPassword, err := common.HashPassword(in.Password)
	if err != nil {
		return nil, err
	}
	in.Password = hashPassword

	// 保存到数据库
	// INSERT INTO `users` (`created_at`,`updated_at`,`username`,`password`,`role`,`label`) VALUES (1717050276,1717050276,'admin04','$2a$04$HUt/vQ3JKS9lorpX/FGQxu2/AsZ2yJjjHZy/CmbbhpB7DITfrblRG',0,'{}')
	// err = c.UserModel().WithContext(ctx).Save(ins).Error
	err = c.UserModel().WithContext(ctx).Create(ins).Error
	if err != nil {
		return nil, exception.ErrorServerInternal("CreateUser 保存失败,%s", err)
	}

	return ins, nil
}

// 查询用户
func (c *UserServiceImpl) QueryUser(ctx context.Context, in *user.QueryUserRequest) (*user.UserSet, error) {

	query := c.UserModel().WithContext(ctx)
	set := user.NewUserSet()

	in.Username = strings.TrimSpace(in.Username)
	if len(in.Username) != 0 {
		query = query.Where("username = ?", in.Username)
	}

	// 先查询total
	err := query.Count(&set.Total).Error
	if err != nil {
		return nil, err
	}

	// 分页
	//
	fmt.Println(in.Offset(), in.PageSize)
	err = query.Offset(in.Offset()).Limit(in.PageSize).Find(&set.Items).Error
	if err != nil {
		return nil, err
	}
	return set, nil
}

func (c *UserServiceImpl) DescribeUser(ctx context.Context, in *user.DescribeUserRequest) (ins *user.User, err error) {

	if in.UserId < 1 && in.Username == "" {
		return nil, user.UserIdNotEmpty
	}

	query := c.UserModel().WithContext(ctx)
	// ins = user.NewUser(user.NewCreateUserRequest())
	if in.UserId > 0 {
		query = c.UserModel().WithContext(ctx).Where("id = ?", in.UserId).First(&ins)
	}
	if len(in.Username) > 0 {
		query = c.UserModel().WithContext(ctx).Where("username = ?", in.Username).First(&ins)

	}
	err = query.Error

	if err != nil {
		// if err.Error() == gorm.ErrRecordNotFound.Error() {
		// 	return nil, exception.ErrorNotFound("DescribeUser记录未找到,%s", err)
		// }
		return nil, err
	}
	return ins, nil
}
